package com.kaifamiao.address;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;

/**
 * IP v4 : 使用的 32 位无符号数字，比如:
 *    192.168.10.250
 *
 * IP v6 : 使用的 128 位无符号数字，比如:
 *    fe80:0000:0000:0000:3922:a657:c169:c52f
 */
public class InetAddressTest {

    public static void main(String[] args) throws UnknownHostException {

        // 获取本地主机的IP地址
        InetAddress local = InetAddress.getLocalHost();
        String hostName = local.getHostName();
        System.out.println( hostName );
        String address = local.getHostAddress();
        System.out.println( address );
        byte[] bytes = local.getAddress();
        System.out.println(Arrays.toString( bytes ));

        // 获得指定名称的主机的所有IP地址
        InetAddress[] addresses = InetAddress.getAllByName( hostName );
        for (int i = 0; i < addresses.length; i++) {
            InetAddress ia = addresses[i];
            System.out.println(ia);
        }

        InetAddress x = InetAddress.getByName( hostName );
        System.out.println( x );

        InetAddress y = InetAddress.getByName( "192.168.0.250" );
        System.out.println( y );

        byte[] ipBytes = { (byte)192, (byte)168, 0, (byte)250 };
        System.out.println(Arrays.toString( ipBytes ));
        InetAddress z = InetAddress.getByAddress( ipBytes );
        System.out.println( z );

    }

}
